//
//  AlarmFaultView.swift
//  xgwjinterconnection
//  故障报警页面
//  Created by WangWeiShuo on 2025/8/18.
//

import SwiftUI
import Combine

struct FaultAlarmView: View {
    @Environment(\.dismiss) var dismiss
    // 用于切换整车/发动机
    @State private var selectedVehEngine = 0
    // 用于切换实时故障/历史故障
    @State private var selectedFaultType = 0
    
    @StateObject private var socketManager = SocketManager.shared
    @State private var cancellables = Set<AnyCancellable>()
    // 用于存储定时器订阅
    @State private var cancellable: AnyCancellable?
    // 控制定时器状态
    @State private var isRunning: Bool = false
    
    @State private var vehicleFaultList: [VehicleFaultBean]? = []
    @State private var engineFaultList: [EngineFaultBean]? = []
    
    enum FaultType: Equatable{
        case vehicleReal
        case vehicleHis
        case engineReal
        case engineHis
    }
    
    @State private var faultType = FaultType.vehicleReal
    
    var body: some View {
        VStack(spacing: 10) {
            
            WikaNavigationView(showBackIcon: true, title: NSLocalizedString("fault_info", comment: "故障报警"),onBack: {
                dismiss() }).frame(maxHeight: 65)
            
            HStack{
                CustomSegmentedControl(options: [NSLocalizedString("fault_vehicle", comment: "整车"), NSLocalizedString("fault_engine", comment: "发动机")], selectedIndex: $selectedVehEngine, height: 50).frame(height: 50)
                    .onChange(of: selectedVehEngine) { newValue in
                        print("1111 selectedVehEngine = \(selectedVehEngine)")
                        print("1111 selectedFaultType = \(selectedFaultType)")
                        print("1111 newValue = \(newValue)")
                        if(selectedFaultType == 0){
                            self.faultType = newValue == 0 ? .vehicleReal : .engineReal
                        }else{
                            self.faultType = newValue == 0 ? .vehicleHis : .engineHis
                        }
                        print("1111 faultType = \(faultType)")
                        getFaultInfo()
                    }
                    .frame(maxWidth: .infinity)
                
                Spacer().frame(maxWidth: .infinity)
            }
            .background(Color(.systemGray5))
            .cornerRadius(10)
            .padding(.horizontal)
            .padding(.top,-25)
            
            CustomSegmentedControl(options: [NSLocalizedString("fault_real", comment: "实时故障"),NSLocalizedString("fault_history", comment: "历史故障")], selectedIndex: $selectedFaultType, height: 50).padding(.horizontal).frame(height: 50)
                .onChange(of: selectedFaultType) { newValue in
                    print("2222 selectedVehEngine = \(selectedVehEngine)")
                    print("2222 selectedFaultType = \(selectedFaultType)")
                    print("2222 newValue = \(newValue)")
                    if(selectedVehEngine == 0){
                        self.faultType = newValue == 0 ? .vehicleReal : .vehicleHis
                    }else{
                        self.faultType = newValue == 0 ? .engineReal : .engineHis
                    }
                    print("2222 faultType = \(faultType)")
                    getFaultInfo()
                }

            // 故障列表
            switch(faultType){
            case .vehicleReal:
                VehicleRealFaultView(vehicleRealFaultList: vehicleFaultList)
            case .vehicleHis:
                VehicleHisFaultView(vehicleHisFaultList: vehicleFaultList)
            case .engineReal:
                EngineRealFaultView(engineRealFaultList: engineFaultList)
            case .engineHis:
                EngineHisFaultView(engineHisFaultList: engineFaultList)
            }
            Spacer()
        }
        .navigationTitle("")
        .navigationBarBackButtonHidden()
        .enableSwipeBackGesture()
        .onAppear {
            // 订阅用户信息消息
            socketManager.subscribeToVehicleFault()
                .receive(on: DispatchQueue.main)
                .sink {  info in
                    vehicleFaultList?.append(contentsOf: info ?? [])
                    print("故障列表 = \(vehicleFaultList?.count)")
                }
                .store(in: &cancellables)
            
            socketManager.subscribeToEngineFault()
                .receive(on: DispatchQueue.main)
                .sink {  info in
                    engineFaultList?.append(contentsOf: info ?? [])
                }
                .store(in: &cancellables)
            
            SendMsgUtils.sendGetMessage(socket: socketManager,type: SendMessageType.GET_MSG_VEHICLE_REAL_ALARM)
        }
        .onDisappear{
        }
    }
    
    private func getFaultInfo(){
        var sendType = SendMessageType.GET_MSG_VEHICLE_REAL_ALARM
        switch(faultType){
        case .vehicleReal:
            vehicleFaultList = []
            sendType = SendMessageType.GET_MSG_VEHICLE_REAL_ALARM
        case .vehicleHis:
            vehicleFaultList = []
            sendType = SendMessageType.GET_MSG_VEHICLE_HISTORY_ALARM
        case .engineReal:
            engineFaultList = []
            sendType = SendMessageType.GET_MSG_ENGINE_REAL_ALARM
        case .engineHis:
            engineFaultList = []
            sendType = SendMessageType.GET_MSG_ENGINE_HISTORY_ALARM
        }
        SendMsgUtils.sendGetMessage(socket: socketManager, type: sendType)
    }
    
}

//整车实时故障布局
struct VehicleRealFaultView: View {
    let vehicleRealFaultList: [VehicleFaultBean]?
    var body: some View {
        VStack(alignment: .leading) {
            ProportionHStack(proportions: [1,2,2,2],spacing: 8) {
                Text("No")
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text(NSLocalizedString("fault_code", comment: "系统代码"))
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text(NSLocalizedString("fault_part_no", comment: "零部件号"))
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text(NSLocalizedString("fault_mode", comment: "故障模式"))
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
            }
            .frame(height: 50)
            .padding(.horizontal)
            .background(Color("blue_126dca1a"))
            
            // 模拟故障数据，可根据实际从数据源获取
            List(Array(vehicleRealFaultList!.enumerated()), id: \.element.id) { index, item in
                ProportionHStack(proportions: [1,2,2,2],spacing: 8) {
                    Text("\(index + 1)").frame(maxWidth:.infinity,alignment:.center)
                    Text(item.code.substring(from: 1, to: 1)).frame(maxWidth:.infinity,alignment:.center)
                    Text(item.code.substring(from: 2, to: 4)).frame(maxWidth:.infinity,alignment:.center)
                    Text(item.code.substring(from: 5, to: 6)).frame(maxWidth:.infinity,alignment:.center)
                }
//                .padding(.horizontal)
                .listRowSeparator(.hidden)
                .listRowBackground(Color.clear)
                .listRowInsets(EdgeInsets(
                    top: 0,
                    leading: 10,  // 左边距，默认约20
                    bottom: 0,
                    trailing: 10  // 右边距，默认约20
                ))
            }
            .scrollContentBackground(.hidden)
            .background(Color.clear)
            .listStyle(.plain)
//            ForEach(0..<10, id: \.self) { index in
//                ProportionHStack(proportions: [1,2,2,2],spacing: 8) {
//                    Text("\(index)").frame(maxWidth:.infinity,alignment:.center)
//                    Text("E100").frame(maxWidth:.infinity,alignment:.center)
//                    Text("245").frame(maxWidth:.infinity,alignment:.center)
//                    Text("03").frame(maxWidth:.infinity,alignment:.center)
//                }
//                .padding(.horizontal)
//            }
        }
        .padding(.horizontal)
    }
}

//整车历史故障布局
struct VehicleHisFaultView: View {
    let vehicleHisFaultList: [VehicleFaultBean]?
    var body: some View {
        VStack(alignment: .leading) {
            ProportionHStack(proportions: [1,2,2,2,2],spacing: 8) {
                Text("No")
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text(NSLocalizedString("fault_code", comment: "系统代码"))
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text(NSLocalizedString("fault_part_no", comment: "零部件号"))
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text(NSLocalizedString("fault_mode", comment: "故障模式"))
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text(NSLocalizedString("fault_time", comment: "发生时间"))
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
            }
            .frame(height: 50)
            .background(Color("blue_126dca1a"))
            
            // 模拟故障数据，可根据实际从数据源获取
//            ForEach(0..<10, id: \.self) { index in
//                ProportionHStack(proportions: [1,2,2,2,2],spacing: 8) {
//                    Text("\(index)").frame(maxWidth:.infinity,alignment:.center)
//                    Text("E100").frame(maxWidth:.infinity,alignment:.center)
//                    Text("245").frame(maxWidth:.infinity,alignment:.center)
//                    Text("03").frame(maxWidth:.infinity,alignment:.center)
//                    Text("2024-07-23 18:13:00")
//                        .font(.footnote)
//                }
//            }
            List(Array(vehicleHisFaultList!.enumerated()), id: \.element.id) { index, item in
                ProportionHStack(proportions: [1,2,2,2,2],spacing: 8) {
                    Text("\(index + 1)").frame(maxWidth:.infinity,alignment:.center)
                    Text(item.code.substring(from: 1, to: 1)).frame(maxWidth:.infinity,alignment:.center)
                    Text(item.code.substring(from: 2, to: 4)).frame(maxWidth:.infinity,alignment:.center)
                    Text(item.code.substring(from: 5, to: 6)).frame(maxWidth:.infinity,alignment:.center)
                    Text(item.time ?? "").frame(maxWidth:.infinity,alignment:.center)
                }
//                .padding(.horizontal)
                .listRowSeparator(.hidden)
                .listRowBackground(Color.clear)
                .listRowInsets(EdgeInsets(
                    top: 0,
                    leading: 10,  // 左边距，默认约20
                    bottom: 0,
                    trailing: 10  // 右边距，默认约20
                ))
            }
            .scrollContentBackground(.hidden)
            .background(Color.clear)
            .listStyle(.plain)
        }
        .padding(.horizontal)
    }
}

//发动机实时故障布局
struct EngineRealFaultView: View {
    let engineRealFaultList: [EngineFaultBean]?
    var body: some View {
        VStack(alignment: .leading) {
            ProportionHStack(proportions: [1,2,2,2],spacing: 8) {
                Text("No")
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text("SPN")
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text("FMI")
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text("OC")
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
            }
            .frame(height: 50)
            .padding(.horizontal)
            .background(Color("blue_126dca1a"))
            
            // 模拟故障数据，可根据实际从数据源获取
//            ForEach(0..<10, id: \.self) { index in
//                ProportionHStack(proportions: [1,2,2,2],spacing: 8) {
//                    Text("\(index)").frame(maxWidth:.infinity,alignment:.center)
//                    Text("E100").frame(maxWidth:.infinity,alignment:.center)
//                    Text("245").frame(maxWidth:.infinity,alignment:.center)
//                    Text("03").frame(maxWidth:.infinity,alignment:.center)
//                }
//                .padding(.horizontal)
//            }
            List(Array(engineRealFaultList!.enumerated()), id: \.element.id) { index, item in
                ProportionHStack(proportions: [1,2,2,2],spacing: 8) {
                    Text("\(index + 1)").frame(maxWidth:.infinity,alignment:.center)
                    Text(item.spn).frame(maxWidth:.infinity,alignment:.center)
                    Text(item.fmi).frame(maxWidth:.infinity,alignment:.center)
                    Text(item.oc).frame(maxWidth:.infinity,alignment:.center)
                }
                .listRowSeparator(.hidden)
                .listRowBackground(Color.clear)
                .listRowInsets(EdgeInsets(
                    top: 0,
                    leading: 10,  // 左边距，默认约20
                    bottom: 0,
                    trailing: 10  // 右边距，默认约20
                ))
            }
            .scrollContentBackground(.hidden)
            .background(Color.clear)
            .listStyle(.plain)
        }
        .padding(.horizontal)
    }
}

//发动机历史故障布局
struct EngineHisFaultView: View {
    let engineHisFaultList: [EngineFaultBean]?
    var body: some View {
        VStack(alignment: .leading) {
            ProportionHStack(proportions: [1,2,2,2,2],spacing: 8) {
                Text("No")
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text("SPN")
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text("FMI")
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text("OC")
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
                Text("Time")
                    .font(.headline)
                    .frame(maxWidth:.infinity,alignment:.center)
            }
            .frame(height: 50)
            .background(Color("blue_126dca1a"))
            
            // 模拟故障数据，可根据实际从数据源获取
            List(Array(engineHisFaultList!.enumerated()), id: \.element.id) { index, item in
                ProportionHStack(proportions: [1,2,2,2,2],spacing: 8) {
                    Text("\(index + 1)").frame(maxWidth:.infinity,alignment:.center)
                    Text(item.spn).frame(maxWidth:.infinity,alignment:.center)
                    Text(item.fmi).frame(maxWidth:.infinity,alignment:.center)
                    Text(item.oc).frame(maxWidth:.infinity,alignment:.center)
                    Text(item.time ?? "").frame(maxWidth:.infinity,alignment:.center)
                }
//                .padding(.horizontal)
                .listRowSeparator(.hidden)
                .listRowBackground(Color.clear)
                .listRowInsets(EdgeInsets(
                    top: 0,
                    leading: 10,  // 左边距，默认约20
                    bottom: 0,
                    trailing: 10  // 右边距，默认约20
                ))
            }
            .scrollContentBackground(.hidden)
            .background(Color.clear)
            .listStyle(.plain)
        }
        .padding(.horizontal)
    }
}

//#Preview {
//    FaultAlarmView()
//}
